package com.hui.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.constant.IndexConstants;
import com.hui.entity.dao.StoreCart;
import com.hui.entity.dao.StoreProduct;
import com.hui.entity.dao.StoreProductAttrValue;
import com.hui.entity.enums.AppHttpCodeEnum;
import com.hui.entity.enums.CartTypeEnum;
import com.hui.entity.enums.OrderInfoEnum;
import com.hui.entity.enums.ShopCommonEnum;
import com.hui.entity.vo.StoreCartQueryVo;
import com.hui.entity.vo.StoreProductVo;
import com.hui.handler.exception.SystemException;
import com.hui.mapper.StoreCartMapper;
import com.hui.service.StoreCartService;
import com.hui.service.StoreProductAttrValueService;
import com.hui.service.StoreProductService;
import com.hui.util.BeanCopyUtils;
import com.hui.util.ResponseResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车表(StoreCart)表服务实现类
 *
 * @author hui
 * @since 2022-07-19 12:01:17
 */
@RequiredArgsConstructor
@Service("storeCartService")
public class StoreCartServiceImpl extends ServiceImpl<StoreCartMapper, StoreCart> implements StoreCartService {

    private final StoreProductService productService;//商品表(StoreProduct)
    private final StoreProductAttrValueService storeProductAttrValueService;//商品属性值表
    private final StoreCartMapper storeCartMapper;

    /**
     * @param uid               用户id
     * @param productId         商品id
     * @param cartNum           购物车数量
     * @param productAttrUnique 产品规格唯一的ID
     * @param isNew             是否新购买
     * @param combinationId     产品拼团ID
     * @param seckillId         产品秒杀ID
     * @param bargainId         产品砍价ID
     * @return
     */
    @Override
    public long addCart(Long uid, Long productId, Integer cartNum, String productAttrUnique, Integer isNew, Long combinationId, Long seckillId, Long bargainId) {
        //判断商品是否上架，库存是否充足
        this.checkProductStock(uid, productId, cartNum, productAttrUnique, combinationId, seckillId, bargainId);
        //获取商品规格信息，是否已经在用户的购物车中
        LambdaQueryWrapper<StoreCart> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StoreCart::getUid, uid)
                .eq(StoreCart::getIsPay, OrderInfoEnum.PAY_STATUS_0.getValue()) //支付状态 OrderInfoEnum.PAY_STATUS_0 未支付
                .eq(StoreCart::getProductId, productId).eq(StoreCart::getIsNew, isNew) //是否新购买
                .eq(StoreCart::getProductAttrUnique, productAttrUnique) //产品规格唯一的ID
                .eq(StoreCart::getBargainId, bargainId) //产品砍价ID
                .eq(StoreCart::getCombinationId, combinationId) // 产品拼团ID
                .eq(StoreCart::getSeckillId, seckillId) // 产品秒杀ID
                .orderByDesc(StoreCart::getId) //按购物车ID排序
                //.last 拼接在最后
                .last(IndexConstants.CART_LIMIT);
        StoreCart cart = getOne(wrapper);
        //将用户传来的信息构造成对象
        StoreCart storeCart = StoreCart.builder()
                .cartNum(cartNum)
                .productAttrUnique(productAttrUnique)
                .productId(productId)
                .bargainId(bargainId)
                .combinationId(combinationId)
                .seckillId(seckillId)
                .isNew(isNew)
                .uid(uid)
                .build();

        if (cart != null) {
            //购物车存在，添加数量
            if (CartTypeEnum.NEW_0.getValue().equals(isNew)) {
                storeCart.setCartNum(cartNum + cart.getCartNum());
            }
            //设置修改的ID
            storeCart.setId(cart.getId());
            this.updateById(storeCart);
        } else {
            this.save(storeCart);
        }

        return storeCart.getId();
    }


    /**
     * 判断商品是否上架，库存是否充足
     *
     * @param uid               用户id
     * @param productId         商品id
     * @param cartNum           购物车数量
     * @param productAttrUnique 产品规格唯一的ID
     * @param combinationId     产品拼团ID
     * @param seckillId         产品秒杀ID
     * @param bargainId         产品砍价ID
     */
    @Override
    public void checkProductStock(Long uid, Long productId, Integer cartNum, String productAttrUnique, Long combinationId, Long seckillId, Long bargainId) {
        Date now = new Date();
        StoreProduct product; //商品表(StoreProduct)表实体类
        int stock;//商品的库存
        if (combinationId != null && combinationId > 0L) {
            //产品拼团
        } else if (seckillId != null && seckillId > 0L) {
            //产品秒杀
        } else if (bargainId != null && bargainId > 0L) {
            //产品砍价
        } else {
            //查找显示的商品
            product = this.productService.lambdaQuery().eq(StoreProduct::getId, productId).eq(StoreProduct::getIsShow, ShopCommonEnum.SHOW_1.getValue()).one();
            if (product == null) {
                throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "该产品已下架或删除");
            }
            //查找显示的商品库存是否充足
            stock = this.productService.getProductStock(productId, productAttrUnique, "");
            if (stock < cartNum) {
                throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "库存不足" + cartNum);
            }
        }
    }

    /**
     * 获取购物车列表
     *
     * @param uid     用户ID
     * @param cartIds 购物车单个商品的IDl
     * @param status  是否新品
     * @return
     */
    @Override
    public ResponseResult getUserProductCartList(Long uid, List cartIds, Integer status) {
        LambdaQueryWrapper<StoreCart> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StoreCart::getUid, uid)
                .eq(StoreCart::getIsPay, OrderInfoEnum.PAY_STATUS_0.getValue())//未购买
                .orderByDesc(StoreCart::getId);
        if (status == null) {
            //是否为立即购买
            //0, "加入购物车" //1, "加入购物车直接购买"
            wrapper.eq(StoreCart::getIsNew, CartTypeEnum.NEW_0.getValue());
        }
        //准备创建订单时查找对应的的商品
        if (ObjectUtil.isNotEmpty(cartIds)) {
            wrapper.in(StoreCart::getId, cartIds);
        }
        List<StoreCart> carts = list(wrapper);
        List<StoreCartQueryVo> valid = new ArrayList();
        List<StoreCartQueryVo> invalid = new ArrayList(); //不支持购买的商品
        Iterator var8 = carts.iterator();
        //开始处理购物车数据
        while (true) {
            while (var8.hasNext()) {
                StoreCart storeCart = (StoreCart) var8.next();
                StoreProductVo storeProduct = null;
                //用ID查询当个商品的信息,并拷贝
                StoreProduct storeProductById = this.productService.getById(storeCart.getProductId());
                storeProduct = BeanCopyUtils.copyBean(storeProductById, StoreProductVo.class);
                //将购物车信息 放置到 购物车视图中（VO）
                StoreCartQueryVo storeCartQueryVo = BeanCopyUtils.copyBean(storeCart, StoreCartQueryVo.class);
                //进行判断
                if (ObjectUtil.isNull(storeProduct)) {
                    //说明商品信息查不到，删除购物车该ID的信息
                    this.removeById(storeCart.getId());
                } else if (
                        ShopCommonEnum.SHOW_0.getValue().equals(storeProduct.getIsShow()) //未上架
                                || storeProduct.getStock() == 0 //库存为0
                                && StrUtil.isEmpty(storeCart.getProductAttrUnique())//判断商品属性是否为空，这个值是商品规格的唯一值
                ) {
                    //放置商品信息，返回信息
                    storeCartQueryVo.setProductInfo(storeProduct);
                    invalid.add(storeCartQueryVo);//不支持购买的商品
                } else if
                (
                        StrUtil.isNotEmpty(storeCart.getProductAttrUnique()) //商品属性存在，这个值是商品规格的唯一值
                ) {
                    //获取商品规格信息
                    LambdaQueryWrapper<StoreProductAttrValue> queryWrapper = new LambdaQueryWrapper();
                    queryWrapper.eq(StoreProductAttrValue::getUnique, storeCart.getProductAttrUnique());
                    //商品规格信息
                    StoreProductAttrValue productAttrValue = storeProductAttrValueService.getOne(queryWrapper);
                    //商品规格信息存在并且库存不等于零
                    if (!ObjectUtil.isNull(productAttrValue) && productAttrValue.getStock() != 0) {
                        //设置商品规格信息
                        storeProduct.setAttrInfo(productAttrValue);
                        storeCartQueryVo.setProductInfo(storeProduct);
                        /*设置商品价格*/
                        storeCartQueryVo.setTruePrice(productAttrValue.getPrice().doubleValue());//商品真实价格(实付的价格)
                        storeCartQueryVo.setVipTruePrice(productAttrValue.getPrice().doubleValue());//vip价格
                        storeCartQueryVo.setCostPrice(productAttrValue.getCost().doubleValue());//成本价
                        /*设置会员价格end*/
                        //设置库存
                        storeCartQueryVo.setTrueStock(Math.toIntExact(productAttrValue.getStock()));
                        valid.add(storeCartQueryVo);
                    } else {
                        storeCartQueryVo.setProductInfo(storeProduct);//设置商品信息
                        invalid.add(storeCartQueryVo);//不支持购买的商品
                    }
                } else {
                    double vipPrice = storeProduct.getPrice().doubleValue();//真实价格
                    storeCartQueryVo.setTruePrice(vipPrice);//真实价格
                    storeCartQueryVo.setVipTruePrice(vipPrice);//vip真实价格
                    storeCartQueryVo.setCostPrice(storeProduct.getCost().doubleValue());//成本价
                    storeCartQueryVo.setTrueStock(storeProduct.getStock());//真实库存
                    storeCartQueryVo.setProductInfo(storeProduct);//设置商品信息
                    valid.add(storeCartQueryVo);
                }
            }
            Map<String, Object> map = new LinkedHashMap();
            map.put("valid", valid); //有效商品
            map.put("invalid", invalid); //无效商品
            return ResponseResult.okResult(map);
        }
    }

    /**
     * @param cartId  购物车ID
     * @param cartNum 商品数量
     * @param uid     用户ID
     * @return
     */
    @Override
    public ResponseResult changeUserCartNum(Long cartId, Integer cartNum, Long uid) {
        StoreCart cart = this.lambdaQuery().eq(StoreCart::getUid, uid)
                .eq(StoreCart::getId, cartId)
                .one();
        if (cart == null) {
            throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "购物车不存在");
        } else if (cartNum <= 0) {
            throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "库存错误");
        } else {
            //获取库存
            int stock = this.productService.getProductStock(cart.getProductId(), cart.getProductAttrUnique(), "");
            if (stock < cartNum) {
                throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "该产品库存不足" + cartNum);
            } else if (cartNum != cart.getCartNum()) {
                //提交的数量和原数量不相等
                // 修改库存
                StoreCart storeCart = new StoreCart();
                storeCart.setCartNum(cartNum);
                storeCart.setId(cartId);
                updateById(storeCart);
            }
        }
        return ResponseResult.okResult();
    }

    @Override
    public void removeUserCart(Long uid, List<String> ids) {
        List<Long> newids = (List) ids.stream().map(Long::new).collect(Collectors.toList());
        this.storeCartMapper.delete(new LambdaQueryWrapper<StoreCart>().eq(StoreCart::getUid, uid).in(StoreCart::getId, newids));
    }

}

